package com.ucode.admin.cgms.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.ucode.cgms.service.CgmsCompanionCategoryService;
import com.ucode.cgms.service.CgmsCompanionOrderService;
import com.ucode.cgms.service.CgmsCompanionUserService;
import com.ucode.cgms.service.CgmsSpecialZoneService;
import com.ucode.member.service.MemberService;
import com.ucode.model.cgms.CgmsCompanionCategory;
import com.ucode.model.cgms.CgmsCompanionOrder;
import com.ucode.model.cgms.CgmsCompanionUser;
import com.ucode.model.cgms.CgmsSpecialZone;
import com.ucode.model.cgms.convert.CgmsCompanionOrderConvert;
import com.ucode.model.cgms.enums.CgmsCompanionOrderStatusEnum;
import com.ucode.model.cgms.enums.CgmsCompanionReportAuditStateEnum;
import com.ucode.model.cgms.form.CgmsCompanionOrderReportForm;
import com.ucode.model.cgms.vo.CgmsCompanionOrderVO;
import com.ucode.model.member.Member;
import com.ucode.tool.base.Paginator;
import com.ucode.tool.base.ResponseResult;
import com.ucode.tool.base.enums.GlobalResultCodeEnum;
import com.ucode.tool.exception.UcodeServiceException;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.Size;
import java.time.LocalDateTime;
import java.util.*;

/**
 * 陪玩订单管理控制器
 * 
 * @author liliang
 * @version 1.0
 */
@Tag(name = "管理后台 - 陪玩社区系统 - 陪玩订单")
@RestController
@RequestMapping("/cgms/companion-order")
@Validated
public class CgmsCompanionOrderController {

    @Resource
    private MemberService memberService;
    @Resource
    private CgmsCompanionOrderService cgmsCompanionOrderService;
    @Resource
    private CgmsCompanionCategoryService cgmsCompanionCategoryService;
    @Resource
    private CgmsSpecialZoneService cgmsSpecialZoneService;
    @Resource
    private CgmsCompanionUserService cgmsCompanionUserService;

    /**
     * 获取陪玩订单分页列表
     * 
     * @param title 订单标题
     * @param zoneId 专区编号
     * @param categoryId 专区分类编号
     * @param status 订单状态
     * @param serviceUserId 服务人员ID
     * @param memberId 下单会员ID
     * @param createTimeInterval 创建时间区间
     * @param pageNum 页码
     * @param pageSize 每页记录数
     * @return 陪玩订单分页数据
     */
    @GetMapping("/page-list")
    @Operation(summary = "获得陪玩订单分页列表")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:query')")
    public ResponseResult<Paginator<CgmsCompanionOrderVO>> pageList(
            //订单id
            @Schema(description = "订单id") @RequestParam(value = "id",required = false) Long id,
            @Schema(description = "订单标题") @RequestParam(value = "title",required = false) String title,
            @Schema(description = "专区编号") @RequestParam(value = "zoneId",required = false) Long zoneId,
            @Schema(description = "专区分类编号") @RequestParam(value = "categoryId",required = false) Long categoryId,
            @Schema(description = "订单状态") @RequestParam(value = "status",required = false) Integer status,
            @Schema(description = "服务人员ID") @RequestParam(value = "serviceUserId",required = false) Long serviceUserId,
            @Schema(description = "下单会员ID") @RequestParam(value = "memberId",required = false) Long memberId,
            @Schema(description = "创建时间区间",example = "[2022-07-01 00:00:00,2022-07-01 23:59:59]") 
            @RequestParam(value = "createTimeInterval",required = false) LocalDateTime[] createTimeInterval,
            @Schema(description = "页码",example="1") @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
            @Schema(description = "每页记录数",example="10") @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

        Map<String,Object> condition = new HashMap<>();
        if(StrUtil.isNotBlank(title))
            condition.put("title", StrUtil.concat(true, "%", title, "%")); // 使用前后模糊匹配
        if(ArrayUtil.isNotEmpty(createTimeInterval) && createTimeInterval.length == 2){
            condition.put("startTime",createTimeInterval[0]);
            condition.put("endTime",createTimeInterval[1]);
        }
        condition.put("id",id);
        condition.put("zoneId",zoneId);
        condition.put("categoryId",categoryId);
        condition.put("status",status);
        condition.put("serviceUserId",serviceUserId);
        condition.put("memberId",memberId);
        condition.put("deltag",false);

        Paginator<CgmsCompanionOrder> paginator = cgmsCompanionOrderService.queryPageForList(condition,pageSize,pageNum);
        return ResponseResult.success(processOrderPageList(paginator));
    }

    /**
     * 获取陪玩订单详情
     * 
     * @param id 订单ID
     * @return 订单详情
     */
    @GetMapping("/getById/{id}")
    @Parameter(description="订单ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @Operation(summary = "获取陪玩订单详情")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:query')")
    public ResponseResult<CgmsCompanionOrderVO> getById(@PathVariable(name="id",required=true) Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        
        CgmsCompanionOrder order = cgmsCompanionOrderService.validate(id);
        CgmsCompanionOrderVO orderVO = CgmsCompanionOrderConvert.INSTANCE.convert(order);
        // 填充关联信息
        enrichOrderVO(orderVO);
        return ResponseResult.success(orderVO);
    }

    /**
     * 陪玩单分配
     * 
     * @param orderId 订单ID
     * @param userId 陪玩用户ID
     * @return 操作结果
     */
    @PostMapping("/designate/{orderId}/{userId}")
    @Operation(summary = "陪玩单分配")
    @Parameter(description="订单ID",name = "orderId", required = true,in = ParameterIn.PATH,example = "1024")
    @Parameter(description="陪玩用户ID",name = "userId", required = true,in = ParameterIn.PATH,example = "2048")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:update')")
    public ResponseResult<Object> designateOrder(
            @PathVariable(name="orderId",required=true) Long orderId,
            @PathVariable(name="userId",required=true) Long userId) {
        
        if (ObjectUtil.isNull(orderId) || ObjectUtil.isNull(userId)) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        // 验证陪玩用户存在
        cgmsCompanionUserService.validate(userId);
        cgmsCompanionOrderService.designateOrder(userId, orderId);
        return ResponseResult.success();
    }

    /**
     * 确认陪玩单完成
     * 
     * @param id 订单ID
     * @return 操作结果
     */
    @PostMapping("/confirm-completed/{id}")
    @Operation(summary = "确认陪玩单完成")
    @Parameter(description="订单ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:update')")
    public ResponseResult<Object> confirmCompleted(@PathVariable(name="id",required=true) Long id) {
        if (ObjectUtil.isNull(id)) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        // 系统确认完工，内部会验证订单状态
        cgmsCompanionOrderService.confirmCompleted(null, id);
        return ResponseResult.success();
    }

    /**
     * 审核陪玩报备
     * 
     * @param id 订单ID
     * @param form 报备审核表单
     * @return 操作结果
     */
    @PostMapping("/audit-report/{id}")
    @Operation(summary = "审核陪玩报备")
    @Parameter(description="订单ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:update')")
    public ResponseResult<Object> auditReport(
            @PathVariable(name="id",required=true) Long id,
            @Valid @RequestBody CgmsCompanionOrderReportForm form) {
        
        if (ObjectUtil.isNull(id) || ObjectUtil.isNull(form.getAuditState())) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        
        // 验证审核状态是否合法
        CgmsCompanionReportAuditStateEnum auditStateEnum = CgmsCompanionReportAuditStateEnum.getByCode(form.getAuditState());
        if (auditStateEnum == null) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED, "审核状态不合法");
        }
        
        // 调用服务层的auditReport方法
        boolean result = cgmsCompanionOrderService.auditReport(id, 
                form.getAuditState(), 
                form.getProcessorId(), 
                form.getProcessorType(), 
                form.getProcessRemark());
        
        return result ? ResponseResult.success() : ResponseResult.failed();
    }

    /**
     * 更新订单备注
     * 
     * @param id 订单ID
     * @param remark 备注内容
     * @return 操作结果
     */
    @PostMapping("/update-remark/{id}")
    @Operation(summary = "更新订单备注")
    @Parameter(description="订单ID",name = "id", required = true,in = ParameterIn.PATH,example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:update')")
    public ResponseResult<Object> updateRemark(
            @PathVariable(name="id",required=true) Long id,
            @RequestParam(name="remark",required=true) String remark) {
        
        if (ObjectUtil.isNull(id)) {
            throw new UcodeServiceException(GlobalResultCodeEnum.VALIDATE_FAILED);
        }
        int i = cgmsCompanionOrderService.updateRemark(id, remark);
            return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    /**
     * 转移订单到回收站
     * 
     * @param id 订单ID
     * @return 操作结果
     */
    @PostMapping("/logic-delete/{id}")
    @Operation(summary = "转移到回收站")
    @Parameter(description="订单ID",name = "id", required = true,in = ParameterIn.PATH, example = "1024")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:logic-delete')")
    public ResponseResult<Object> logicDelete(@PathVariable(name="id",required=true) Long id) {
            cgmsCompanionOrderService.validate(id);
            int i = cgmsCompanionOrderService.logicDeletePrimaryKey(id);
            return i > 0 ? ResponseResult.success() : ResponseResult.failed();

    }

    /**
     * 批量转移订单到回收站
     * 
     * @param ids 订单ID集合
     * @return 操作结果
     */
    @PostMapping("/batch-logic-delete")
    @Operation(summary = "批量转移到回收站")
    @PreAuthorize("@usfs.hasPermission('cgms:companion-order:logic-delete')")
    public ResponseResult<Boolean> batchLogicDeletePrimaryKey(
            @Schema(description = "编号集合",requiredMode = Schema.RequiredMode.REQUIRED)
            @NotEmpty(message = "编号集合为空")
            @Size(min = 1,max = 20,message = "编号集合数量为1-20条")
            @RequestParam(value = "ids",required = true) List<Long> ids) {

            int i = cgmsCompanionOrderService.logicDeleteByPrimaryKeys(ids);
            return i > 0 ? ResponseResult.success() : ResponseResult.failed();
    }

    /**
     * 处理订单分页数据，填充关联信息
     * 
     * @param paginator 订单分页数据
     * @return 填充关联信息后的订单分页数据
     */
    private Paginator<CgmsCompanionOrderVO> processOrderPageList(Paginator<CgmsCompanionOrder> paginator) {
        if (paginator == null || CollUtil.isEmpty(paginator.getList())) {
            return new Paginator<>();
        }
        
        Paginator<CgmsCompanionOrderVO> paginatorVO = CgmsCompanionOrderConvert.INSTANCE.convertPage(paginator);
        
        if(CollUtil.isNotEmpty(paginatorVO.getList())) {
            Set<Long> memberIds = new HashSet<>();
            Set<Long> serviceUserIds = new HashSet<>();
            Set<Long> zoneIds = new HashSet<>();
            Set<Long> categoryIds = new HashSet<>();
            
            // 收集ID
            for(CgmsCompanionOrderVO vo : paginatorVO.getList()){
                if (ObjUtil.isNotNull(vo.getMemberId())) {
                    memberIds.add(vo.getMemberId());
                }
                
                if(ObjUtil.isNotNull(vo.getServiceUserId()) && !ObjUtil.equals(vo.getServiceUserId(), 0L)) {
                    serviceUserIds.add(vo.getServiceUserId());
                }
                
                if(ObjUtil.isNotNull(vo.getZoneId()) && !ObjUtil.equals(vo.getZoneId(), 0L)) {
                    zoneIds.add(vo.getZoneId());
                }
                
                if(ObjUtil.isNotNull(vo.getCategoryId()) && !ObjUtil.equals(vo.getCategoryId(), 0L)) {
                    categoryIds.add(vo.getCategoryId());
                }
            }
            
            // 批量查询
            Map<Long, Member> memberMap = CollUtil.isEmpty(memberIds) ? new HashMap<>() : memberService.getMap(memberIds);
            Map<Long, CgmsCompanionUser> serviceUserMap = CollUtil.isEmpty(serviceUserIds) ? new HashMap<>() : cgmsCompanionUserService.getMap(serviceUserIds);
            Map<Long, CgmsSpecialZone> zoneMap = CollUtil.isEmpty(zoneIds) ? new HashMap<>() : cgmsSpecialZoneService.getMap(zoneIds);
            Map<Long, CgmsCompanionCategory> categoryMap = CollUtil.isEmpty(categoryIds) ? new HashMap<>() : cgmsCompanionCategoryService.getMap(categoryIds);
            
            // 填充数据
            for(CgmsCompanionOrderVO vo : paginatorVO.getList()) {
                // 填充会员信息
                if (ObjUtil.isNotNull(vo.getMemberId())) {
                    Member member = memberMap.get(vo.getMemberId());
                    if(ObjUtil.isNotNull(member)) {
                        vo.setMemberNickname(member.getNickname());
                        vo.setMemberAvatar(member.getAvatar());
                    }
                }
                
                // 填充服务人员信息
                if(ObjUtil.isNotNull(vo.getServiceUserId()) && !ObjUtil.equals(vo.getServiceUserId(), 0L)) {
                    CgmsCompanionUser serviceUser = serviceUserMap.get(vo.getServiceUserId());
                    if(ObjUtil.isNotNull(serviceUser)) {
                        if(ObjUtil.isNotNull(serviceUser)) {
                            vo.setServiceUserNickname(serviceUser.getNickName());
                            vo.setServicePhone(serviceUser.getPhone());
                            vo.setServiceUserAvatar(serviceUser.getAvatar());
                        }
                    }
                }
                
                // 填充专区信息
                if(ObjUtil.isNotNull(vo.getZoneId()) && !ObjUtil.equals(vo.getZoneId(), 0L)) {
                    CgmsSpecialZone zone = zoneMap.get(vo.getZoneId());
                    if(ObjUtil.isNotNull(zone)) {
                        vo.setZoneName(zone.getName());
                    }
                }
                
                // 填充分类信息
                if(ObjUtil.isNotNull(vo.getCategoryId()) && !ObjUtil.equals(vo.getCategoryId(), 0L)) {
                    CgmsCompanionCategory category = categoryMap.get(vo.getCategoryId());
                    if(ObjUtil.isNotNull(category)) {
                        vo.setCategoryName(category.getName());
                    }
                }
                
                // 设置订单状态名称
                CgmsCompanionOrderStatusEnum statusEnum = CgmsCompanionOrderStatusEnum.get(vo.getStatus());
                if(ObjUtil.isNotNull(statusEnum)) {
                    vo.setStatusName(statusEnum.getMessage());
                }
            }
        }
        
        return paginatorVO;
    }
    
    /**
     * 填充单个订单VO的关联信息
     * 
     * @param vo 订单VO对象
     */
    private void enrichOrderVO(CgmsCompanionOrderVO vo) {
        if (vo == null) {
            return;
        }
        
        // 填充会员信息
        if(ObjUtil.isNotNull(vo.getMemberId())) {
            Member member = memberService.selectByPrimaryKey(vo.getMemberId());
            if(ObjUtil.isNotNull(member)) {
                vo.setMemberNickname(member.getNickname());
                vo.setMemberAvatar(member.getAvatar());
            }
        }
        
        // 填充服务人员信息
        if(ObjUtil.isNotNull(vo.getServiceUserId()) && !ObjUtil.equals(vo.getServiceUserId(), 0L)) {
            CgmsCompanionUser serviceUser = cgmsCompanionUserService.selectByPrimaryKey(vo.getServiceUserId());
            if(ObjUtil.isNotNull(serviceUser)) {
                vo.setServiceUserNickname(serviceUser.getNickName());
                vo.setServicePhone(serviceUser.getPhone());
                vo.setServiceUserAvatar(serviceUser.getAvatar());
            }
        }
        
        // 填充专区信息
        if(ObjUtil.isNotNull(vo.getZoneId()) && !ObjUtil.equals(vo.getZoneId(), 0L)) {
            CgmsSpecialZone zone = cgmsSpecialZoneService.selectByPrimaryKey(vo.getZoneId());
            if(ObjUtil.isNotNull(zone)) {
                vo.setZoneName(zone.getName());
            }
        }
        
        // 填充分类信息
        if(ObjUtil.isNotNull(vo.getCategoryId()) && !ObjUtil.equals(vo.getCategoryId(), 0L)) {
            CgmsCompanionCategory category = cgmsCompanionCategoryService.selectByPrimaryKey(vo.getCategoryId());
            if(ObjUtil.isNotNull(category)) {
                vo.setCategoryName(category.getName());
            }
        }
        
        // 设置订单状态名称
        CgmsCompanionOrderStatusEnum statusEnum = CgmsCompanionOrderStatusEnum.get(vo.getStatus());
        if(ObjUtil.isNotNull(statusEnum)) {
            vo.setStatusName(statusEnum.getMessage());
        }
    }
}